package edu.nf.ch10.service;

import edu.nf.ch10.dto.Message;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author wangl
 * @date 2025/9/19
 *
 * 消息的发布服务
 */
@Service
public class PublishService {
    /**
     * 注入SimpMessagingTemplate，用于发布消息
     */
    private SimpMessagingTemplate template;

    public PublishService(SimpMessagingTemplate template) {
        this.template = template;
    }

    /**
     * 消息投递
     * @param message
     */
    public void sendMessage(String topic, String message) {
        Message msg = new Message();
        msg.setContent(message);
        msg.setSendDate(new Date());
        //将消息发布到Broker中，/news是配置的前缀，/message是自定义的路径
        template.convertAndSend("/" +topic+ "/message", msg);
    }
}